#include <p16F887.inc>

	__CONFIG    _CONFIG1, _LVP_OFF & _FCMEN_OFF & _IESO_OFF & _BOR_OFF & _CPD_OFF & _CP_OFF & _MCLRE_OFF & _PWRTE_ON & _WDT_OFF & _INTRC_OSC_NOCLKOUT
	__CONFIG    _CONFIG2, _WRT_OFF & _BOR21V

     cblock     0x20
     Display
     W_Temp
     STATUS_Temp
     d1
     d2
     d3
     flag
     endc

    org 0

Start:
    BSF STATUS,RP0 ; Bank 1
    MOVLW b'00000111' ; configure Timer0. Sourced from the
    ; Processor clock
    MOVWF OPTION_REG ; Maximum Prescaler
    CLRF TRISD ; Make PortD all output
    CLRF Display
    BCF STATUS,RP0 ; Bank 0
    BCF         INTCON,T0IF ; flag must be cleared in software
    clrf        flag

TimerLoop:
    BTFSC       flag,0
    BCF         INTCON,T0IF
    BTFSS       INTCON,T0IF ; wait here until Timer0 rolls over
    GOTO        Convert
    BCF         INTCON,T0IF ; flag must be cleared in software
    BCF         flag,0
    GOTO        BlinkLoop
    ;GOTO        TimerLoop

Convert:
    NOP
    NOP
    NOP
    NOP
    NOP
    BANKSEL     ADCON0
    MOVLW       0x41        ;configure analog conversion
    MOVWF       ADCON0
    BSF         ADCON0,0    ;turn ADC on
    BSF         ADCON0,1    ;begin ADC
    BTFSS       ADCON0,1    ;loop until ADC is complete
    GOTO        $-1
    MOVFW       ADRESH      ;move the ADRESH into temp variable prior to operations
    ANDLW       b'11111110'
    MOVWF       Display
    MOVWF       PORTD
    GOTO        TimerLoop

BlinkLoop:
    
    clrf        Display
    bsf         Display,0
    movfw       Display
    movwf       PORTD
    call        Delay
    bcf         Display,0
    movfw       Display
    movwf       PORTD
    call        Delay
    BTFSC       INTCON,T0IF
    BSF         flag,0
    BTFSC       flag,0
    GOTO        TimerLoop
    goto        BlinkLoop

Delay:
			;999990 cycles
	movlw	0x07
	movwf	d1
	movlw	0x2F
	movwf	d2
	movlw	0x03
	movwf	d3
Delay_0:
	decfsz	d1, f
	goto	$+2
	decfsz	d2, f
	goto	$+2
	decfsz	d3, f
	goto	Delay_0

			;6 cycles
	goto	$+1
	goto	$+1
	goto	$+1

			;4 cycles (including call)
	return

RestoreContext:
    ;incorrect context restore
    MOVF STATUS_Temp,w
    MOVWF STATUS
    MOVF W_Temp ;this may change the Z bit
    ;in the Status register
    ;good context restore
    MOVF STATUS_Temp,w
    MOVWF STATUS
    SWAPF W_Temp,f ;swap in place
    SWAPF W_Temp,w ;swap with Wreg destination
    end